﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Sgml;

namespace iReaper.IndexBuilder.WWESource
{
    /// <summary>
    /// WWERootParser will analysis http://www.microsoft.com/events/series/default.mspx, get all category information
    /// </summary>
    public class WWERootParser
    {
        public ChannelInfo[] GetChannelInfo()
        {
            string url = System.Configuration.ConfigurationSettings.AppSettings["WWERootUrl"];

            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            string strContent = client.DownloadString(url);

            SgmlReader reader = new SgmlReader();
            reader.InputStream = new StringReader(strContent);

            // Reach <div id=contentTableDIV>
            while (reader.Read())
            {
                if (reader.Name == "div" && reader.GetAttribute("id") == "contentTableDIV")
                {
                    // Call 
                    while (reader.Read())
                    {
                        if (reader.Name == "div")
                        {
                            string xml = reader.ReadInnerXml();
                            ChannelInfo[] channels = ParseContentXml(xml);

                            return channels;
                        }
                    }
                }
            }

            return new ChannelInfo[0];
        }

        private ChannelInfo[] ParseContentXml(string contentXml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(contentXml);
            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace("ns", "http://www.microsoft.com/MSCOM/MNP2/Schemas");
            //
            XmlNodeList tables = doc.SelectNodes(".//ns:span[@class='refLabelH3']", mgr);
            List<ChannelInfo> infoList = new List<ChannelInfo>();
            foreach (XmlNode tpNode in tables)
            {
                XmlNode channelNode = tpNode.ParentNode; // This is a td node in current 

                // Create channel info object
                ChannelInfo channel = new ChannelInfo();
                List<ChannelInfoItem> list = new List<ChannelInfoItem>();
                
                // Get channel Name
                XmlNode nChannelName = channelNode.SelectSingleNode("ns:span[@class='refLabelH3']", mgr);
                channel.Name = nChannelName.InnerText;

                // Get all links in a list
                XmlNodeList nAddrs = channelNode.SelectNodes(".//ns:a", mgr);
                foreach (XmlNode nAddr in nAddrs)
                {
                    string url;
                    string category;

                    XmlAttribute aHref = nAddr.Attributes["href"];
                    if (aHref != null)
                    {
                        // create channel item object
                        ChannelInfoItem item = new ChannelInfoItem();
                        item.Channel = channel; // link to current channel
                        url = aHref.Value;
                        category = nAddr.InnerText.Trim();

                        Uri uri;
                        if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
                        {
                            if (uri.IsAbsoluteUri)
                            {
                                item.Url = url;
                            }
                            else
                            {
                                item.Url = new Uri(Common.MSFT, uri).AbsoluteUri;
                            }
                        }
                        item.Category = category;
                        list.Add(item);
                    }
                }

                channel.Items = list.ToArray();
                infoList.Add(channel);
            }

            return infoList.ToArray();
        }

       
    }


   
}
